package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/*
 * 定时任务类
 * */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /*每分钟检查一次待支付的订单*/
    @Scheduled(cron = "0 * * * * *")
    public void processTimeoutOrder() {
        log.info("处理支付超时订单：{}", LocalDateTime.now());
        // 查询订单的待支付订单，判断是否超时,查询订单状态是"待支付"并且下单时间超过15min的所有订单
        List<Orders> ordersList = orderMapper.getOrderByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if (!ordersList.isEmpty()) {
            // 集合非空
            for (Orders orders : ordersList) {
                // 获取订单id
                Long orderId = orders.getId();
                // 更新订单状态为已取消，取消原因为"订单超时"
                Orders ordersNew = Orders.builder().id(orderId).status(Orders.CANCELLED).cancelReason("订单超时").cancelTime(LocalDateTime.now()).build();
                orderMapper.update(ordersNew); // 修改订单状态
            }
        }
    }

    /*修改长时间配送中的订单*/
    @Scheduled(cron = "0 1 * * * *")
    public void processDeliveryOrder() {
        log.info("处理超时订单：{}", LocalDateTime.now());
        // 获取订单状态为"派送中"的订单和下单时是昨天的订单
        List<Orders> ordersList = orderMapper.getOrderByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().minusDays(1));
        if (!ordersList.isEmpty()) {
            // 集合非空
            for (Orders orders : ordersList) {
                // 获取订单id
                Long orderId = orders.getId();
                // 更新订单状态为已完成，取消原因为"订单超时"
                Orders ordersNew = Orders.builder().build();
                orderMapper.update(ordersNew); //修改订单状态
            }
        }
    }
}
